package cc.leap.service;

import cc.leap.constant.ScheduleConstants;
import cc.leap.mapper.SysJobMapper;
import cc.leap.model.PageQuery;
import cc.leap.model.TableDataInfo;
import cc.leap.model.domain.SysJob;
import cc.leap.utils.ScheduleUtils;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.solon.service.impl.ServiceImpl;
import org.noear.solon.annotation.Component;
import org.noear.solon.annotation.Inject;
import org.noear.solon.data.annotation.Tran;
import org.quartz.JobDataMap;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;

import static cc.leap.model.domain.table.SysJobTableDef.SYS_JOB;

/**
 * SysJobService
 *
 * @author leap
 * @date 2024/8/21
 */
@Component
public class SysJobService extends ServiceImpl<SysJobMapper, SysJob> {
    @Inject
    private Scheduler scheduler;

    @Inject
    private SysJobMapper jobMapper;

    private QueryWrapper buildQueryWrapper(SysJob job) {
        QueryWrapper queryWrapper = QueryWrapper.create()
                .select(SYS_JOB.JOB_ID, SYS_JOB.JOB_NAME, SYS_JOB.JOB_GROUP, SYS_JOB.INVOKE_TARGET, SYS_JOB.CRON_EXPRESSION, SYS_JOB.MISFIRE_POLICY, SYS_JOB.CONCURRENT, SYS_JOB.STATUS, SYS_JOB.CREATE_TIME);

        return queryWrapper;
    }

    public TableDataInfo<SysJob> selectJobPage(SysJob sysJob) {
        QueryWrapper queryWrapper = buildQueryWrapper(sysJob);
        Page<SysJob> page = this.pageAs(PageQuery.build(), queryWrapper, SysJob.class);
        return TableDataInfo.build(page);
    }

    public SysJob selectJobById(Long jobId) {
        return jobMapper.selectJobById(jobId);
    }

    @Tran
    public boolean run(SysJob job) throws SchedulerException {
        boolean result = false;
        Long jobId = job.getJobId();
        String jobGroup = job.getJobGroup();
        SysJob properties = selectJobById(job.getJobId());
        // 参数
        JobDataMap dataMap = new JobDataMap();
        dataMap.put(ScheduleConstants.TASK_PROPERTIES, properties);
        JobKey jobKey = ScheduleUtils.getJobKey(jobId, jobGroup);
        System.out.println(scheduler.getCurrentlyExecutingJobs().size());
        if (scheduler.checkExists(jobKey)) {
            result = true;
            scheduler.triggerJob(jobKey, dataMap);
        }
        return result;
    }


}
